package com.jetpackframework.webview;

import android.content.Context;
import android.os.RemoteException;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.blankj.utilcode.util.GsonUtils;
import com.jetpackframework.ContextUtil;
import com.jetpackframework.IMainProcessToWebViewInsterface;


public class BaseWebView extends WebView{
    private final IMainProcessToWebViewInsterface.Stub CALLBACK = new IMainProcessToWebViewInsterface.Stub() {
        @Override
        public void onResult(String callBackName, String params) throws RemoteException {
            Log.e("onResult", "callbackName=" + callBackName + ",params=" + params);
            if (callBackName != null)
                BaseWebView.this.handleCallback(callBackName, params);
        }
    };

    public BaseWebView(Context context) {
        super(context);
        init();
    }

    public BaseWebView(Context context, AttributeSet attrs) {
        super(context,attrs);
        init();
    }

    public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }
    private void init(){
        WebViewCommandDispatcher.getInstance().initConnection();
        WebViewDefaultSettings.getInstance().setSettings(this);
        addJavascriptInterface(this,"jsToAndroid");
    }
    public void registerCallBack(WebViewCallBack callBack){
        setWebChromeClient(new WebViewChromeCallBack(callBack));
        setWebViewClient(new WebViewClient(callBack));
    }
    @JavascriptInterface
    public void takeNativeAction(String params){
        Log.e("BaseWebView","takeNativeAction params:"+params);
        WebViewCommand command = GsonUtils.fromJson(params,WebViewCommand.class);
        if (command != null){
            Log.e("BaseWebView","command:"+command);
            if (command.isProcess) {
                WebViewCommandDispatcher.getInstance().execCommand(command, CALLBACK);
            }else {
                try {
                    WebViewCommandManager.getInstance().handleWebViewCommand(command.name,command.param.toString(),command.callbackname,CALLBACK);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void handleCallback(final String callBackName, final String params) {
        post(new Runnable() {
            @Override
            public void run() {
                String jscode = "javascript:webjs.callback('" + callBackName + "','" + params + "')";
                Log.e("BaseWebView","jscode="+jscode);
                evaluateJavascript(jscode,null);
            }
        });
    }
}
